import conf.settings as settings
from metric_reader import MetricReader
from lib.metric_type.capacity import CapacityMetric, Level
from lib.metric_exception import MetricSettingsException,\
    MetricCollectException, MetricProcessException

MOUNTPOINT = "/"
NODE_LABEL = settings.NODE_LABEL


# node roootfs inode util = (100 - f_favail/f_files * 100)
class NodeRootfsInodeUtil(CapacityMetric):
    def __init__(self, metric_reader: MetricReader,
                 metric_settings, level: Level):
        super().__init__(metric_reader, metric_settings, level)

    def _collect_process_metric(self):
        metric_name = self.settings.collect.metric_name
        node_tag = self.settings.collect.node_tag_name

        if self.level != Level.Node:
            raise MetricSettingsException(
                f'{metric_name} is a node level metric!'
            )

        avail_value = self.settings.collect.related_value[0]
        files_value = self.settings.collect.related_value[1]
        query_args = {
            NODE_LABEL: self.name[Level.Node],
            node_tag: avail_value,
            "mount": MOUNTPOINT
        }

        favail_res = self._get_custom_metric(metric_name,
                                             **query_args)

        query_args[node_tag] = files_value
        files_res = self._get_custom_metric(metric_name,
                                            **query_args)

        if not len(favail_res.data) == len(files_res.data) == 1:
            raise MetricCollectException(
                f"Collect {metric_name},"
                f" Level: {self.level} from Prometheus failed!"
            )

        try:
            max_favail = max(
                [float(item[1])
                 for item in favail_res.data[0].to_dict()["values"]]
            )
            max_files = max(
                [float(item[1])
                 for item in files_res.data[0].to_dict()["values"]]
            )
            final_value = (100 - max_favail / max_files * 100)

        except Exception as exc:
            raise MetricProcessException from exc

        return final_value
